package com.supreme.commonboot.handler;

import com.alibaba.fastjson.JSONObject;
import com.supreme.commonboot.exception.BizException;
import com.supreme.commonboot.utils.AjaxResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestControllerAdvice(basePackages = {
        "com.supreme.simpleserver.controller",
        "com.supreme.bizorderserver.controller",
        "com.supreme.bizstockserver.controller",
        "com.supreme.studyserver.controller",
        "com.supreme.swaggerserver.controller",
        "com.supreme.uploadserver.controller",
        "com.supreme.threadserver.controller",
        "com.supreme.securityserver.controller",
})
public class GlobalExceptionHandler {

    @Resource
    private HttpServletRequest request;

    @ExceptionHandler(value = NullPointerException.class)
    public JSONObject nullPointerHandler(HttpServletRequest request, NullPointerException exception) {
        log.error("⛔nullPointerHandler⛔");
        return AjaxResp.instance(1, exception.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public JSONObject exceptionHandler(HttpServletRequest request, Exception exception) {
        log.error("⛔exceptionHandler⛔");
        return AjaxResp.instance(1, exception.getMessage());
    }

    @ExceptionHandler(value = RuntimeException.class)
    public JSONObject runtimeExceptionHandler(HttpServletRequest request, RuntimeException exception) {
        log.error("⛔runtimeExceptionHandler⛔");
        return AjaxResp.instance(1, exception.getMessage());
    }

    @ExceptionHandler(value = BizException.class)
    public JSONObject bizExceptionHandler(HttpServletRequest request, BizException exception) {
        String requestURI = request.getRequestURI();
        log.error("⛔bizExceptionHandler: {}⛔", requestURI);
        return AjaxResp.instance(exception.getCode(), exception.getMessage())
                .append("URI", requestURI);
    }
}
